var searchTypeArray = []
$('.nav-search ul li a').each(function () { searchTypeArray.push($(this).text());})
/* 选择搜索的条件触发函数 */
$('.nav-search ul li a').click(function () {
    $wrapper = $('#searchWrapper')
    $wrapper.html('')
    const searchType = $(this).text();
    /* 添加地址 */
    if(searchType === '详细地址'){
        $wrapper.html(`<div class="pt-2">
            省份
            <select name="searchProv">
                <option value="*" data-code="*">请选择</option>
            </select>
            市区
            <select name="searchCity">
                <option value="*" data-code="*">请选择</option>
            </select>
            地区
            <select name="searchArea">
                <option value="*" data-code="*">请选择</option>
            </select>
            详细地址
            <input name="searchDetail">
        </div>`)
        loadSearchAddress()
    } else if(searchType === '名称'){
        $wrapper.html('<input id="input-search-text" type="text" name="searchUserName"' +
            ' class="bg-light w-auto mx-1" placeholder="支持正则表达式">')
    } else if(searchType === '性别'){
        $wrapper.html('<select name="searchGender">\n' +
            '<option value="男">男</option>\n' +
            '<option value="女">女</option>\n' +
            '</select>')
    } else if(searchType === '生日'){
        $wrapper.html('从&nbsp;' +
            '<input type="date" name="searchBirthdayBegin" value="2022-02-14">' +
            '&nbsp;至&nbsp;' +
            '<input type="date" name="searchBirthdayEnd" value="2022-02-14">')
    } else if(searchType === '电话'){
        $wrapper.html('<input id="input-search-text" type="text" name="searchPhone"' +
            ' class="bg-light w-auto mx-1" placeholder="支持正则表达式">')
    } else if(searchType === 'ID'){
        $wrapper.html('范围&nbsp;' +
            '<input type="number" name="searchIDBegin" value="1">' +
            '&nbsp;—&nbsp;</div>' +
            '<input type="number" name="searchIDEnd" value="1">\n')
    }
    $('#label-search-type').text(searchType)
})

/*省市区三级联动*/
/* 省市三级联动 */
// 获取用户的信息
var $selectProv
var $selectCity
var $selectArea
var $inputDetail
function loadSearchAddress() {
    $selectProv = $("select[name='searchProv']")
    $selectCity = $("select[name='searchCity']")
    $selectArea = $("select[name='searchArea']")
    $inputDetail = $('input[name="searchDetail"]')
    // 初始化省市区
    initSearchAddress();
    // 更改省份后的操作
    $selectProv.change(function () {
        let provCode = $(this).children('option:selected').data('code');
        searchGetCity(provCode);
    });

    // 更改城市后的操作
    $selectCity.change(function () {
        // var cityCode = $("select[name='city']").val();
        let cityCode = $(this).children('option:selected').data('code');
        searchGetArea(cityCode);
    });
}

function initSearchAddress() {
    // ajax请求所有省份
    $.get({
        url: "/getProvinces",
        dataType: 'JSON',
        error: (err) => {
            alert('获取省份失败.')
            console.error(err.responseText)
        },
        success: (data) => {
            $.each(data, function(i, d) {
                $selectProv.append(
                    "<option value='" + d.name + "' data-code='"+ d.code + "\'>" + d.name+ "</option>");
            });
            searchGetCity('*');
        }
    });

}

//获取对应城市列表（里面包括获取第一个城市的区县列表）
function searchGetCity(provCode) {
    // 先清空城市下拉框
    $selectCity.empty();
    // ajax请求所有市级单位
    $selectCity.append('<option value="*" data-code="*" selected>请选择</option>')
    if(provCode === '*') {
        searchGetArea('*')
        return
    }
    $.get({
        url: "/getCities",
        data: {provCode:provCode},
        dataType: 'JSON',
        error: (err) => {
            alert('获取市区失败.')
            console.error(err.responseText)
        },
        success: (data) => {
            console.log(data)
            $.each(data, function(i, d) {
                $selectCity.append(
                    "<option value='" + d.name + "' data-code='"+ d.code + "\'>" + d.name + "</option>");
            });
            searchGetArea(data[0].code);
        }
    })
}

function searchGetArea(cityCode) {
    // 先清空区县下拉框
    $selectArea.empty();
    $selectArea.append('<option value="*" data-code="*" selected>请选择</option>')
    if(cityCode === '*') return;
    // ajax请求所有区县单位
    $.get({
        url: '/getAreas',
        data: {cityCode:cityCode},
        dataType: 'JSON',
        error: (err) =>{
            alert('获取地区信息失败.')
            console.error(err.responseText)
        },
        success: (data) => {
            $.each(data, function (i, d) {
                $selectArea.append(
                    "<option value='" + d.name + "' data-code='"+ d.code + "\'>" + d.name + "</option>");
            });
        }
    })
}

/* 动态渲染搜索条件的标签 */
function ualert(searchType, searchText, alertStyle) {
    let wrapper = $('<div class="div-search-condition mx-3 col-md-3 pt-2 pb-1 fade show alert alert-' + alertStyle
        + ' alert-dismissible" role="alert" data-type="' + searchType + '" data-text="' + searchText +'">' +
        searchType + ' :' + searchText + '<button type="button" class="btn-close btn-sm pt-3 pb-1" data-bs-dismiss="alert" aria-label="Close">' +
        '</button></div>')

    $('#searchAlertPlaceholder').append(wrapper)
}
/* 判断搜索的筛选类型是否已经存在 */
function hasSearchType(searchType){
    hasSt = false;
    // 获取当前所有的搜索类型
    $('.div-search-condition').each(function(){
        let t = $(this).data('type')
        if (searchType != null && searchType === t){
            hasSt = true;
            return false;   // 终止循环
        }
    })
    return hasSt;
}
/* 添加筛选标签 */
$('#btn-add-search').click(function(){
    let count = $('.div-search-condition').length

    // 限制1: 筛选标签数量 <=3
    if(count >= 3) {
        open_toast('fail', '目前最多支持添加三个标签')
        return ;
    }
    let searchType = $('#label-search-type').text()
    let searchText = ''
    if(searchType === '名称'){
        searchText = $('input[name="searchUserName"]').val()
    } else if(searchType === '性别'){
        searchText = $('select[name="searchGender"]').val()
    } else if(searchType === '生日'){
        searchText = $('input[name="searchBirthdayBegin"]').val() + '到'
            $('input[name="searchBirthdayEnd"]').val()
    } else if(searchType === '详细地址'){
        searchText = $selectProv.val() + '-' + $selectCity.val() + '-'
            + $selectArea.val() + '-' + ($inputDetail.val() === '' ? '*' : $inputDetail.val())
    } else if(searchType === 'ID'){
        searchText = $('input[name="searchIDBegin"]').val() + '到' +
            $('input[name="searchIDEnd"]').val()
    } else if(searchType === '电话'){
        searchText = $('input[name="searchPhone"]').val()
    }
    // 限制2: 筛选内容不为空
    if(searchText == null || searchText === '')
        open_toast('warning', '请输入筛选的条件')
    // 限制3: 筛选类型不能重复
    else if(hasSearchType(searchType)) {
        open_toast('warning', '当前筛选的类型已存在!')
    } else
        ualert(searchType, searchText, 'success')
})

// 清空标签
$('#btn-clear-search').click(function(){
    if(confirm('确定清空所有的筛选标签吗？'))
        $('.btn-close').click()
})
// 开始搜索
$('#btn-start-search').click(function(){

    // 显示加载图标
    let reqUrl = clearURIExceptPageNow()
    // 封装表单信息
    let reqData = []
    $('.div-search-condition').each(function(){
        reqData.push({
            name: $(this).data('type'),
            value: $(this).data('text')
        })
        reqUrl = updateUrlParam(reqUrl, $(this).data('type'), $(this).data('text'))
    })
    // 将页数默认为第一页
    reqUrl = updateUrlParam(reqUrl, 'pageNow', '1')
    // 更换地址
    window.location = reqUrl
    $.ajax({
        url: '/admin/user/search',
        type: 'POST',
        data: JSON.stringify(reqData),
        dataType: 'JSON',
        contentType: 'application/json;charset=UTF-8',
        error: (err) => {
            open_toast('fail', "请求失败!")
        },
        success: (data) =>{
            if(data['code'] === 1) {
                loadUserInfo(data['response']['usersInfo'])
                loadPageInfo(data['response']['pageInfo'])
                $('#searchSpinnerPlaceholder').html('')
            }
        }
    })
})
